package com.boxtelecom.chat;

import java.util.ArrayList;
import java.util.Iterator;

import com.boxtelecom.adapters.ChatArrayAdapter;
import com.boxtelecom.interfaces.IChatServiceListener;
import com.boxtelecom.mycircle.R;
import com.boxtelecom.services.ChatService;
import com.boxtelecom.services.LocalBinder;
import com.boxtelecom.users.RosterUser;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class Chat extends Activity {

	private ChatService _myService = null;
	private boolean _myBound = false;
	
	private Bundle _contact = null;
	
	private EditText _writeMessage = null;
	private Button _sendMessage = null;
	private ListView _messageList = null;
	
	private Handler _handle = new Handler();
	
	private ChatArrayAdapter _adapter = null;
	
	private final IChatServiceListener _listener = new IChatServiceListener() {
		
		// event received when a message had been received during a chat session
		// print it in the activity
		@Override
		public void receiveMessage(String message) {
			// TODO Auto-generated method stub
			final String tmp = message;
			_handle.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					MyMessage aMessage = new MyMessage();
					if(_contact.getString("name").length()>0){
						aMessage.setUserName(_contact.getString("name") + ": ");
					} else {
						aMessage.setUserName(_contact.getString("user") + ": ");
					}
					
					aMessage.setUserMessage(tmp);
					aMessage.setColorId(getResources().getColor(R.color.blue));
					_adapter.add(aMessage);
				}
			});			
		}

		// event received when a message had been received
		// used in the listingcontacts activity
		@Override
		public void incomingMessage(Bundle data) {
			// TODO Auto-generated method stub
		}

		// event received when the current chat session is finished
		// used in the listingcontacts activity
		@Override
		public void chatFinished(Bundle data) {
			// TODO Auto-generated method stub			
		}

		// event received when the connection to the server had been successfull
		// then proceed to the download of the user profil information
		// used in the listingcontacts activity
		@Override
		public void loginFinished(ArrayList<RosterUser> list) {
			// TODO Auto-generated method stub			
		}

		// event received if an error occurred
		// used in the listingcontacts activity
		@Override
		public void chatError(String error) {
			// TODO Auto-generated method stub		
		}

		// event received when the presence of an user changes
		// used in the listingcontacts activity 
		@Override
		public void presenceChange(RosterUser user) {
			// TODO Auto-generated method stub			
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		
		_writeMessage = (EditText) findViewById(R.id.writeMessage);
		_sendMessage = (Button) findViewById(R.id.sendMessage);
		_messageList = (ListView) findViewById(R.id.chatListView);
		
		_adapter = new ChatArrayAdapter(Chat.this, R.layout.message);
		_messageList.setAdapter(_adapter);
	
		Intent intent = this.getIntent();
		
		_contact = intent.getExtras();
	
		if(_contact.containsKey("listMsg")){
			ArrayList<String> msgs = new ArrayList<String>();
			msgs = _contact.getStringArrayList("listMsg");
			Iterator<String> it = msgs.iterator();
			while(it.hasNext()){
				MyMessage aMsg = new MyMessage();
				String string = it.next();

				aMsg.setUserName(string + ": ");
				if(string.equals(_contact.getString("name"))){
					aMsg.setColorId(getResources().getColor(R.color.blue));
				} else {
					aMsg.setColorId(getResources().getColor(R.color.red));
				}
				
				aMsg.setUserMessage(it.next());
				_adapter.add(aMsg);
			}
		}

		_sendMessage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String msg = _writeMessage.getText().toString();

				if(msg.length()>0){
					
					_myService.sendMessage(msg);
					MyMessage aMsg = new MyMessage();
					if(_contact.containsKey("loginName")){
						aMsg.setUserName(_contact.getString("loginName") + ": ");
					} else {
						aMsg.setUserName(_contact.getString("loggedUser") + ": ");
					}
					
					aMsg.setUserMessage(msg);
					aMsg.setColorId(getResources().getColor(R.color.red));
					
					_adapter.add(aMsg);
					
					_writeMessage.setText("");
				}
			
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			    imm.hideSoftInputFromWindow(_writeMessage.getWindowToken(), 0);				
			}
		});
		
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Intent intent = new Intent(this, ChatService.class);
		bindService(intent, _myConnection, Context.BIND_AUTO_CREATE);		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if(_myBound){
			unbindService(_myConnection);
			_myBound = false;
		}
		_myService.stopChat();
		_myService.removeListener(_listener);
		_myService = null;
		_myConnection = null;
	}
	
	private ServiceConnection _myConnection  = new ServiceConnection() {	
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			_myBound = false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			LocalBinder<ChatService> localBinder = (LocalBinder<ChatService>) service;
			_myService = localBinder.getService();
			_myBound = true;
			_myService.addListener(_listener);
			_myService.createChat(_contact.getString("user"));
		}
	};
}
